package com.zndroid.logcat;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;

import com.zndroid.logcat.core.CatDelegate;

/**
 * Created by lzy on 2021/1/14.
 * API for developer
 * 手动管理
 */
public final class LogcatX {
    private final CatDelegate delegate;

    private LogcatX(){
        delegate = new CatDelegate(getDefaultConfig());
    }
    private static class X {
        final static LogcatX XX = new LogcatX();
    }

    /**
     * get instance
     * */
    public static LogcatX getInstance() {
        return X.XX;
    }

    private Config getDefaultConfig() {
        return new Config();
    }

    /**
     * custom config for developer
     * */
    public void setConfig(@NonNull Config config) {
        this.delegate.setConfig(config);
    }

    public void display(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!Settings.canDrawOverlays(context)) {
                Toast.makeText(context, context.getString(R.string.txt_logcat_overplay_permission_tip), Toast.LENGTH_SHORT).show();

                if (context instanceof Application) {
                    return;
                } else {
                    overlayPermission(context);
                }

                return;
            }
        }
        delegate.showLogcat(context);
    }

    public void close() {
        delegate.closeLogcat();
    }

    public boolean isShow() {
        return delegate.isShow();
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void overlayPermission(Context context) {
        Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
        intent.setData(Uri.parse("package:" + context.getPackageName()));
        context.startActivity(intent);
    }
}
